package com.kyc.kycxkplaygame.view.digital;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.kyc.kycxkplaygame.R;
import com.kyc.kycxkplaygame.activity.digital.DigitalMainActivity;
import com.kyc.kycxkplaygame.entity.digital.DigitalBlockUnit;
import com.kyc.kycxkplaygame.entity.digital.DigitalTetrisBlock;
import com.kyc.kycxkplaygame.util.erluosifangkuai.GameConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/7/16.
 */

public class DigitalMoveRectView extends View {

    /**
     * 俄罗斯方块的最大坐标
     */
    private static int max_x, max_y;
    /**
     * 行数和列数
     */
    private static int num_x = 0, num_y = 0;

    /**
     * 俄罗斯方块的单元块画笔
     */
    private static Paint paintBlock = null;
    private static Paint paintText = null;
    private static final int BOUND_WIDTH_OF_WALL = 1;
    /**
     * 当前正在下落的方块
     */
    private List<DigitalBlockUnit> blockUnits = new ArrayList<DigitalBlockUnit>();
    /**
     * 下一个要显示的方块
     */
    private List<DigitalBlockUnit> blockUnitBufs = new ArrayList<DigitalBlockUnit>();
    /**
     * 下一个要显示的方块
     */
    private List<DigitalBlockUnit> routeBlockUnitBufs = new ArrayList<DigitalBlockUnit>();
    /**
     * 全部的方块allBlockUnits
     */
    private List<DigitalBlockUnit> allBlockUnits = new ArrayList<DigitalBlockUnit>();
    /**
     * 单个可移动方块
     */
    private List<DigitalBlockUnit> oneBlockUnits = new ArrayList<DigitalBlockUnit>();
    /**
     * 单个移动之后的方块
     */
    private List<DigitalBlockUnit> oneMoveBlockUnits = new ArrayList<DigitalBlockUnit>();
    /**
     * 调用此对象的Activity对象
     */
    private DigitalMainActivity father = null;
    private int[] map = new int[100]; // 保存每行网格中包含俄罗斯方块单元的个数
    /**
     * 游戏的主线程
     */
    private Thread mainThread = null;
    // 游戏的几种状态
    /**
     * 标识游戏是开始还是停止
     */
    private boolean gameStatus = false;
    /**
     * 标识游戏是暂停还是运行
     */
    private boolean runningStatus = false;
    /**
     * 方块的中心方块单元的坐标,
     */
    private int xx, yy;
    /**
     * 方块,用户随机获取各种形状的方块
     */
    private DigitalTetrisBlock tetrisBlock;
    /**
     * 分数
     */
    private int score = 0;
    private int lastX;
    private int lastY;
    private int count;

    /**
     * 当前方块的类型
     */
    //private int blockType = 0;
    public DigitalMoveRectView(Context context) {
        this(context, null);
    }

    public DigitalMoveRectView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (paintBlock == null) {// 初始化化背景墙画笔
            paintBlock = new Paint();
            paintBlock.setColor(Color.parseColor("#FF6600"));
        }

        if (paintText == null) {
            paintText = new Paint();
            paintText.setColor(getResources().getColor(R.color.white));
            paintText.setStyle(Paint.Style.FILL);
            paintText.setTextSize(80);
            paintText.setTextAlign(Paint.Align.CENTER);
        }
        tetrisBlock = new DigitalTetrisBlock();
    }


    public void setWidthAndHeight(int width, int height) {
        max_x = width;
        max_y = height;
    }

    /**
     * 设置当前游戏页面的父类activity
     *
     * @param digitalMainActivity
     */
    public void setFather(DigitalMainActivity digitalMainActivity) {
        father = digitalMainActivity;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        RectF rel;
        // 随机产生一个俄罗斯方块
        int len = blockUnits.size();
        // 绘制方块
        for (int i = 0; i < len; i++) {
            int x = blockUnits.get(i).x;
            int y = blockUnits.get(i).y;
            // 设置当前方块的颜色
            paintBlock.setColor(/*color[*/getResources().getColor(blockUnits.get(i).color)/*]*/);
            rel = new RectF(x + BOUND_WIDTH_OF_WALL, y + BOUND_WIDTH_OF_WALL,
                    x + DigitalBlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL, y + DigitalBlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL);
            canvas.drawRoundRect(rel, 8, 8, paintBlock);

            Paint.FontMetrics fontMetrics = paintText.getFontMetrics();
            float top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top
            float bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom

            int baseLineY = (int) (rel.centerY() - top / 2 - bottom / 2);//基线中间点的y轴计算公式

            canvas.drawText(blockUnits.get(i).blockTxt, rel.centerX(), baseLineY, paintText);
        }
        // 随机产生一个俄罗斯方块
        len = allBlockUnits.size();
        // 绘制方块
        for (int i = 0; i < len; i++) {
            int x = allBlockUnits.get(i).x;
            int y = allBlockUnits.get(i).y;
            paintBlock.setColor(/*color[*/getResources().getColor(allBlockUnits.get(i).color)/*]*/);
            rel = new RectF(x + BOUND_WIDTH_OF_WALL, y + BOUND_WIDTH_OF_WALL,
                    x + DigitalBlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL, y + DigitalBlockUnit.UNIT_SIZE - BOUND_WIDTH_OF_WALL);
            canvas.drawRoundRect(rel, 8, 8, paintBlock);

            Paint.FontMetrics fontMetrics = paintText.getFontMetrics();
            float top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top
            float bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom

            int baseLineY = (int) (rel.centerY() - top / 2 - bottom / 2);//基线中间点的y轴计算公式

            canvas.drawText(allBlockUnits.get(i).blockTxt, rel.centerX(), baseLineY, paintText);
        }
        count = (int) ((max_y - 206 - 10) / DigitalBlockUnit.UNIT_SIZE) + 1;

        //getNewBlock();
    }

    private void getNewBlock() {
        // 新的方块的坐标，x坐标位于x轴的中间，y 位于起始位置
        this.xx = 10 + (4 / 2) * DigitalBlockUnit.UNIT_SIZE;
        this.yy = 10;
        if (blockUnitBufs.size() == 0) {
            // 当游戏第一次开始的时候，先初始化一个方块
            DigitalTetrisBlock.EblockType eblockType = DigitalTetrisBlock.EblockType.BLOCK_TYPE_ZERO;
            blockUnitBufs = tetrisBlock.getUnits(xx, yy, eblockType);
        }
        blockUnits = blockUnitBufs;
        DigitalTetrisBlock.EblockType eblockType = DigitalTetrisBlock.EblockType.BLOCK_TYPE_ZERO;
        blockUnitBufs = tetrisBlock.getUnits(xx, yy, eblockType);
    }

    public void startGame() {
        runningStatus = true;
        if (mainThread == null || !mainThread.isAlive()) {
            getNewBlock();
            mainThread = new Thread(new MainThread());
            mainThread.start();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY() - 255;
                Log.i("KYCC", "lastX === " + lastX + "  ,  lastY ==== " + lastY);
                //if (!DigitalBlockUnit.canMoveToDown(blockUnits, max_y, allBlockUnits)) {
                for (DigitalBlockUnit blockUnit : allBlockUnits) {
                    //Log.i("KYCC","block   x === "+ blockUnit.x + "  ,  y ==== " +blockUnit.y);
                    int left = blockUnit.x;
                    int right = blockUnit.x + DigitalBlockUnit.UNIT_SIZE;
                    int top = blockUnit.y;
                    int bottom = blockUnit.y + DigitalBlockUnit.UNIT_SIZE;
                    if (lastX > left && lastX < right && lastY > top && lastY < bottom) {
                        Log.i("KYCC", "block   x === " + blockUnit.x + "  ,  y ==== " + blockUnit.y);
                        oneBlockUnits.add(blockUnit);
                    }
                }
                // }
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - lastX;
                int dy = (int) event.getRawY() - lastY - 255;
                Log.i("KYCC", "dx === " + dx + "  ,  dy ==== " + dy);
                for (DigitalBlockUnit blockUnit : oneBlockUnits) {
                    int left = blockUnit.x + dx;
                    int top = blockUnit.y + dy;
                    int right = blockUnit.x + DigitalBlockUnit.UNIT_SIZE + dx;
                    int bottom = blockUnit.y + DigitalBlockUnit.UNIT_SIZE + dy;
                    if (left < (DigitalBlockUnit.UNIT_SIZE / 2)) {
                        left = blockUnit.x;
                        right = left + DigitalBlockUnit.UNIT_SIZE;
                    }
                    if (right > max_x) {
                        right = max_x;
                        left = right - DigitalBlockUnit.UNIT_SIZE;//getWidth();
                    }
                    if (top < (DigitalBlockUnit.UNIT_SIZE / 2)) {
                        top = blockUnit.y;
                        bottom = top + DigitalBlockUnit.UNIT_SIZE;//getHeight();
                    }
                    if (bottom > max_y) {
                        bottom = max_y;
                        top = bottom - DigitalBlockUnit.UNIT_SIZE;//getHeight();
                    }
                    blockUnit.x = left;
                    blockUnit.y = top;
                    //oneMoveBlockUnits.add(new DigitalBlockUnit(left,top,blockUnit.color,blockUnit.blockTxt));
                    //layout(left, top, right, bottom);
                    //DigitalBlockUnit.removeBlock(allBlockUnits,blockUnit);
                    allBlockUnits.add(blockUnit);
                    //DigitalBlockUnit.toMove(oneMoveBlockUnits,max_x,allBlockUnits);
                }

                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY() - 255;
                break;
            case MotionEvent.ACTION_UP:
                oneBlockUnits.clear();
                father.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        invalidate();
                    }
                });
                break;
            default:
                break;
        }
        return true;
    }

    private class MainThread implements Runnable {

        @Override
        public void run() {
            while (runningStatus) {
                if (DigitalBlockUnit.canMoveToDown(blockUnits, max_y, allBlockUnits)) {
                    // 判断是否可以继续下落，如果可以下落，则下落
                    DigitalBlockUnit.toDown(blockUnits, max_y, allBlockUnits);
                    yy = yy + DigitalBlockUnit.UNIT_SIZE;
                    //count--;
                } else {
                    //不可以继续落下时将方块添加到allBlockUnits列表里
                    for (DigitalBlockUnit blockUnit : blockUnits) {
                        //blockUnit.y = blockUnit.y + DigitalBlockUnit.UNIT_SIZE;
                        allBlockUnits.add(blockUnit);
                    }
                }

                father.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        invalidate();
                    }
                });
                try {
                    Thread.sleep(GameConfig.SPEED);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
